package com.gengyun.gengyunacquistion.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gengyun.gengyunacquistion.mapper.AcquisitionMapper;
import com.gengyun.gengyunacquistion.mapper.AcquisitionUavMapper;
import com.gengyun.gengyunacquistion.pojo.*;
import com.gengyun.gengyunacquistion.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j

public class AcquisitionUavServiceImpl implements IAcquisitionUavService {

    @Autowired
    AcquisitionUavMapper  acquisitionUavMapper;

    @Autowired
    @Qualifier("uavMultispectralImageServiceImpl")
    IUavMultispectralImageService uavMultispectralImageService;


    @Autowired
    IRecordService recordService;

    /**
     * 获取上一次获取数据的时间戳, 用于接着获取数据
     * @return
     */
    public String getLastTimestamp() {
        return acquisitionUavMapper.selectById(4).getLastTimestamp();
    }



    /**
     * 将json数据保存到txt文档中，
     * @Transactional(rollbackFor = Exception.class)
     * @param content  filePath
     */
    public static boolean createJsonFile(String content, String filePath) {

        // 标记文件生成是否成功
        boolean flag = true;
        // 生成json格式文件
        try {
            // 保证创建一个新文件
            File file = new File(filePath);
            if (!file.getParentFile().exists()) { // 如果父目录不存在，创建父目录
                file.getParentFile().mkdirs();
            }
            if (file.exists()) { // 如果已存在,删除旧文件
                file.delete();
            }
            file.createNewFile();
            // 将格式化后的字符串写入文件
            Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            write.write(content);
            write.flush();
            write.close();
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }




    /**
     * 处理接口获取到的json数据, 这里开启事务管理
     * @Transactional(rollbackFor = Exception.class)
     * @param content
     */
    @Transactional(rollbackFor = Exception.class)
    public void JsonHandler(String content, String endTimestamp) {

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Map<String, String> plotCrop = new HashMap<>();
        plotCrop.put( "16085","雪川哈9-新建1");
        plotCrop.put( "16086","雪川哈9-新建2");
        plotCrop.put( "16080","雪川哈6-新建1");
        plotCrop.put( "16081","雪川哈6-新建2");
        plotCrop.put( "16650","雪川哈6-新建3");
        plotCrop.put( "16651","雪川哈6-新建4");
        plotCrop.put( "16652","雪川哈6-新建5");
        plotCrop.put( "16653","雪川哈6-新建6");
        plotCrop.put( "16654","雪川哈6-新建7");



        JSONObject jsonObject = JSON.parseObject(content);

        JSONArray uavMultispectralImages = jsonObject.getJSONArray("data");

        System.out.println(uavMultispectralImages);

        if(uavMultispectralImages!=null)
        {
            List<UavMultispectralImage> uavMultispectralImageslies = handleUavMultispectralImages(uavMultispectralImages);


            /**
             * 如果不是null, 就插入, 否则会报错, 批处理至少要有一条数据
             * 顺便更新一下数据库 endTimestamp 更新的问题
             */
            List<Long> endTimestampUpdate = new ArrayList<>();

            if (uavMultispectralImageslies.size() > 0) {
                uavMultispectralImageService.saveBatch(uavMultispectralImageslies, uavMultispectralImageslies.size());

            }
        }

        System.out.println("结束时间为：");
        System.out.println(endTimestamp);
        recordService.updateById(new RecordTime(4, endTimestamp, sf.format(new Date(Long.parseLong(endTimestamp)))));
//        if (endTimestampUpdate.size() > 0) {
//
//            recordService.updateById(new RecordTime(1, endTimestamp, sf.format(Collections.max(endTimestampUpdate))));
//        }

    }


    /**
     * 静态方法用于处理无人机json数据
     * @param uavMultispectralImages
     * @return
     */
    private static List<UavMultispectralImage> handleUavMultispectralImages(JSONArray uavMultispectralImages) {

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<UavMultispectralImage> UavMultispectralImageList = new ArrayList<>();

        for (int i = 0; i < uavMultispectralImages.size(); i++) {
            JSONObject uavMultispectralImage = (JSONObject) uavMultispectralImages.get(i);
            String archiveUrl = uavMultispectralImage.getString("archiveUrl");
            String cropsRotationPlotID = uavMultispectralImage.getString("cropsRotationPlotID");
            Long performTimestamp = Long.parseLong(uavMultispectralImage.getString("performTimestamp"));



            UavMultispectralImage uav = new UavMultispectralImage(null,
                    archiveUrl,cropsRotationPlotID,performTimestamp
            );

            UavMultispectralImageList.add(uav);


        }
        return UavMultispectralImageList;
    }


}